package com.bizmda.bizsip.source.rest.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizMessage;
import com.bizmda.bizsip.common.BizMessageInterface;
import com.bizmda.bizsip.source.api.SourceClientFactory;
import com.bizmda.bizsip.source.rest.controller.RestSourceDTO;
import com.bizmda.bizsip.source.api.SourceBeanInterface;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RestSourceBean implements SourceBeanInterface {
    private Map<String, BizMessageInterface> appServiceMap = new HashMap<String, BizMessageInterface>();
    private BizMessageInterface errorAppService = SourceClientFactory.getAppServiceClient(BizMessageInterface.class, "/source1/error");

    @Override
    public Object process(Object data) throws BizException {
        BizMessage<JSONObject> bizMessage;
        RestSourceDTO restSourceDTO = (RestSourceDTO) data;
        Map<String,String> headerMap = restSourceDTO.getHeaderMap();
        JSONObject jsonObject = restSourceDTO.getJsonObjectData();
        String serviceId = headerMap.get("service-id");
        if (StrUtil.isEmpty(serviceId)) {
            bizMessage = this.errorAppService.call(jsonObject);
            return bizMessage.getData();
        }
        BizMessageInterface appService = this.appServiceMap.get(serviceId);
        if (appService == null) {
            appService = SourceClientFactory.getAppServiceClient(BizMessageInterface.class, serviceId);
            this.appServiceMap.put(serviceId, appService);
        }
        bizMessage = appService.call(jsonObject);
        return bizMessage.getData();
    }
}
